import { forwardRef, HttpException, HttpStatus, Inject, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository} from 'typeorm';
import { AuthService } from '../auth/auth.service';
import {MsgService} from "@/modules/common/msg/msg.service";
import {RoleEntity} from "@/modules/role/entities/role.entity";
import { LoginLogEntity } from '@/modules/log/entities/loginLog.entity';
import { ArtEntity } from '@/modules/art/entities/art.entity';
import { UserEntity } from "@/modules/user/entities/user.entity";


@Injectable()
export class HomeService {
  constructor(
    //依赖注入
    @InjectRepository(UserEntity) private readonly userEntity:Repository<UserEntity>,
    @InjectRepository(RoleEntity) private readonly roleEntity:Repository<RoleEntity>,
    @InjectRepository(LoginLogEntity) private readonly logEntity:Repository<LoginLogEntity>,
    @InjectRepository(ArtEntity) private readonly artEntity:Repository<ArtEntity>,
    @Inject(forwardRef(() => AuthService)) private readonly authService:AuthService,
    private readonly msgService:MsgService
  ) {}

  //后台访问人数总数
  async accessStatistics(){
    let loginLogTotal;
    try {
      loginLogTotal = await this.logEntity.createQueryBuilder().getCount()
    }catch (error) {
      return this.msgService.fail(error);
    }
    return this.msgService.success(loginLogTotal==0?"0":loginLogTotal);
  }

  //文章总数
  async artStatistics(){
    let artTotal;
    try {
      artTotal = await this.artEntity.createQueryBuilder().getCount()
    }catch (error) {
      return this.msgService.fail(error);
    }
    return this.msgService.success(artTotal==0?"0":artTotal);
  }

  //访问人数时间段
  async accessTimeSlot(arr:string[]){
    let loginLogArr = []
    try {
      for(let i in arr){
        let curTime = new Date(arr[i]).getTime()
        let tomorrowTime = new Date(arr[i]).getTime()+(24 * 60 * 60 * 1000)
        let curNum = await this.logEntity.createQueryBuilder().where("addTime > :curTime AND addTime < :tomorrowTime", { curTime,tomorrowTime }).getCount()
        loginLogArr.push({
          curDate:arr[i],
          curNum
        })
      }
    }catch (error) {
      return this.msgService.fail(error);
    }
    return this.msgService.success(loginLogArr??[]);
  }

}
